﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;

using Server.Functions;

namespace Server.Login
{
    public sealed class LoginMgr : Singleton<LoginMgr>
    {
        Dictionary<Guid, LoginData> m_dictAccounts = null;

        public LoginMgr()
        {
            m_dictAccounts = new Dictionary<Guid, LoginData>();
        }

        public LoginResult CheckLogin(string usn, string pwd, out Guid guid)
        {
            guid = Guid.Empty;

            int uid = LoginConn.CheckLogin(usn, pwd);
            if (-1 == uid)
            {
                return LoginResult.ERROR;
            }

            if (IsLogined(usn))
            {
                return LoginResult.ALREADIN;
            }

            LoginData lgData = new LoginData();
            lgData.guid = Guid.NewGuid();
            lgData.uid = uid;
            lgData.usn = usn;

            guid = lgData.guid;
            m_dictAccounts[guid] = lgData;

            return LoginResult.OK;
        }

        public bool IsLogined(string usn)
        {
            foreach (KeyValuePair<Guid, LoginData> kv in m_dictAccounts)
            {
                if (kv.Value.usn == usn)
                {
                    return true;
                }
            }
            return false;
        }

        public void Logout(Guid guid)
        {
            m_dictAccounts.Remove(guid);
        }

        public LoginData GetLoginDataByGuid(Guid guid)
        {
            return m_dictAccounts[guid];
        }
    }
}
